import { getRepository } from 'typeorm';
import { NextFunction, Request, Response } from 'express';
import { Post } from '../entity/Post';
import { successRes, failRes } from '../utils/response';
export class PostController {
    private postRepository = getRepository(Post);
    async list(request: Request, response: Response, next: NextFunction) {
        try {
            const { pageNo, pageSize, title, auth, createdDate } = request.query;
            var data = [];
            var total = 0;
            let queryBuilder = this.postRepository.createQueryBuilder('post');
            if (title) {
                queryBuilder = queryBuilder.andWhere('post.title like :title', { title: '%' + title + '%' });
            }
            if (auth) {
                queryBuilder = queryBuilder.andWhere('post.auth like :auth', { auth: '%' + auth + '%' });
            }
            if (createdDate) {
                queryBuilder = queryBuilder.andWhere(`post.createdDate >= :after and post.createdDate <= :before`, {
                    after: createdDate.split(' ')[0] + ' 00:00:00',
                    before: createdDate.split(' ')[0] + ' 23:59:59',
                });
            }

            queryBuilder = queryBuilder.leftJoinAndSelect('post.user', 'user');
            queryBuilder = queryBuilder.skip((pageNo - 1) * pageSize).take(pageSize);
            queryBuilder = queryBuilder.orderBy('post.createdDate', 'DESC');
            // const sql = await queryBuilder.getSql();
            // console.log('sql', sql);
            data = await queryBuilder.getMany();
            total = await queryBuilder.getCount();

            let result = {
                current: pageNo,
                records: data,
                size: pageSize,
                total: total,
            };
            return successRes(result);
        } catch (error) {
            console.log(`error`, error)
            return failRes(error);
        }

    }


    async one(request: Request, response: Response, next: NextFunction) {
        try {
            console.log('request.query.id', request.query)
            let result = await this.postRepository.findOne(request.query.id);
            return successRes(result);
        } catch (error) {
            return failRes(error);
        }

    }

    async add(request: Request, response: Response, next: NextFunction) {
        try {
            const toSave = request.body;
            let obj = await this.postRepository.save(toSave);
            if (obj.id) {
                return successRes('添加成功');
            } else {
                return failRes('添加失败');
            }
        } catch (error) {
            return failRes(error);
        }
    }
    async edit(request: Request, response: Response, next: NextFunction) {
        try {
            const toSave = request.body;
            let result = await this.postRepository.findOne(toSave.id);
            if (result) {
                await this.postRepository.save(toSave);
                return successRes('编辑成功');
            } else {
                return failRes({}, 500, '未找到该记录');
            }
        } catch (error) {
            return failRes(error);
        }
    }


    async remove(request: Request, response: Response, next: NextFunction) {
        try {
            let newsToRemove = await this.postRepository.findOne(request.query.id);
            if (newsToRemove) {
                await this.postRepository.remove(newsToRemove);
                return successRes({}, '删除成功');
            } else {
                return failRes({}, 500, '未找到该记录');
            }
        } catch (error) {
            return failRes(error);
        }
    }
    async websitePostList(request: Request, response: Response, next: NextFunction) {
        try {
            let result = await this.postRepository.find({ where: { status: 1 }, relations: ['user'] });
            return successRes(result);
        } catch (error) {
            return failRes(error);
        }
    }
    async websitePostAdd(request: Request, response: Response, next: NextFunction) {
        try {
            const toSave = request.body;
            let obj = await this.postRepository.save(toSave);
            if (obj.id) {
                return successRes('添加成功');
            } else {
                return failRes('添加失败');
            }
        } catch (error) {
            return failRes(error);
        }
    }
    async websitePostDetail(request: Request, response: Response, next: NextFunction) {
        try {
            const { postId } = request.query;
            let result = await this.postRepository.findOne({ where: { id: postId }, relations: ['user'] });
            return successRes(result);
        } catch (error) {
            return failRes(error);
        }

    }
}
